package com.cjm.one.common.config.mybatisPlus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cjm.one.common.utils.AuthSysUserContextHolder;
import com.cjm.one.common.utils.RequestPathContextHolder;
import com.cjm.one.model.system.entity.SysUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ClassUtils;

import java.time.LocalDateTime;
import java.util.Objects;

//自动填充配置
@Component
@Slf4j
public class MybatisPlusAutoMetaObjectHandler implements MetaObjectHandler{
    private static final AntPathMatcher pathMatcher = new AntPathMatcher();


    @Override
    public void insertFill(MetaObject metaObject) {

        String path = RequestPathContextHolder.getPath();
        boolean isAppPath = pathMatcher.match("/app/**", path);
        boolean isAdminPath = pathMatcher.match("/admin/**", path);

        LocalDateTime now = LocalDateTime.now();
        Long userId = null;

        // 管理员路径才填充用户信息
        if (isAdminPath) {
            SysUserInfo user = AuthSysUserContextHolder.getAuthContextSysUser();
            if (user != null) {
                userId = user.getId();
                log.info("管理员路径填充用户ID：{}", userId);
                autoFillValue("tenantId", userId, metaObject);
                autoFillValue("createBy", userId, metaObject);
                autoFillValue("updateBy", userId, metaObject);
            }
        }

        // 所有路径都填充时间字段
        autoFillValue("createTime", now, metaObject);
        autoFillValue("updateTime", now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String path = RequestPathContextHolder.getPath();
        boolean isAdminPath = pathMatcher.match("/admin/**", path);

        Long userId = null;
        if (isAdminPath) {
            SysUserInfo user = AuthSysUserContextHolder.getAuthContextSysUser();
            if (user != null) {
                userId = user.getId();
                log.info("管理员路径更新操作人：{}", userId);
                autoFillValue("updateBy", userId, metaObject);
            }
        }

        autoFillValue("updateTime", LocalDateTime.now(), metaObject);
    }
    //自动填充值
    public static void autoFillValue(String fillName, Object fillValue, MetaObject metaObject){
        //判断填充值是否为空
       if (fillValue == null){
           return;
       }
       log.info("自动填充的字段名：{}",fillName);
       //判断是否包含该字段
       if (!metaObject.hasSetter(fillName)){
        return;
       }
       log.info("自动填充的值：{}",fillValue);

        //当填充字段和填充值的类型相同才填充
        Class<?> getterType = metaObject.getGetterType(fillName);
        log.info("自动填充的字段类型：{}",getterType);
//        if (ClassUtils.isAssignableValue(getterType, fillValue)) {
            log.info("填充成功");
            metaObject.setValue(fillName, fillValue);
//        }


    }


}
